from typing import List
from fastapi import APIRouter,HTTPException,status
from starlette.responses import JSONResponse

from database.model import Question,SheetItem
from .model import SheetItemModel

router=APIRouter(tags=['answer sheet'],prefix='/answersheet')

@router.get('/year/{year}',response_model=List[SheetItemModel])
def get_questions_by_year(year:int):
     return list(
         SheetItem.select()
         .join(Question)
         .where(Question.year==year)
         .order_by(Question.order.asc()))


@router.get('/chapter/{chapter_id}',response_model=List[SheetItemModel])
def get_question_by_chapter(chapter_id:int):
    if chapter_id<1000:
        raise HTTPException(status_code=status.HTTP_404_NOT_FOUND,detail=f'Chapter id[{chapter_id}] not allowed!')
    return list(SheetItem.select().join(Question).where(Question.chapter==chapter_id))


@router.get('/update/{question_id}',response_model=SheetItemModel)
def update_question_answer_sheet(question_id:int,is_right:bool):
    sheet_item:SheetItem=SheetItem.get(SheetItem.question_id==question_id)
    sheet_item.check_count+=1
    if is_right:
        sheet_item.right_count+=1
        sheet_item.last_check_right=True
    else:
        sheet_item.last_check_right=False
    sheet_item.save()
    return sheet_item